<?php
namespace app\mxty\model;

use think\Model;
use think\model\concern\SoftDelete;
use app\common\model\UploadFile;
use app\common\model\User;
use app\common\enum\order\PayStatus as OrderPayStatusEnum;

class CourseOrder extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $table = 'athlon_course_order';
    protected $pk = 'order_id';

    public function image()
    {
        return $this->hasOne(UploadFile::class, 'file_id', 'image_id');
    }

    public function course()
    {
        return $this->hasOne(Course::class, 'course_id', 'course_id');
    }

    public function user()
    {
        return $this->hasOne(User::class, 'user_id', 'user_id');
    }

    public static function order($data)
    {
        return self::create($data);
    }

    public static function getInfoByOderNo($order_no)
    {
        return self::where('order_no', $order_no)->find();
    }

    public function getCoursesByUserId($user_id)
    {
        return self::with(['image', 'course', 'course.coachs', 'course.coachs.image'])->where('user_id', $user_id)->where('pay_status', OrderPayStatusEnum::SUCCESS)->select();
    }

    public function countStudentNum($course_id)
    {
        return $this->where('course_id', $course_id)->where('pay_status', OrderPayStatusEnum::SUCCESS)->count();
    }

    // 根据多个课程id获取所有学员（去重）
    public function getStudentsByCoursesId($coursesIds)
    {
        return $this->with(['user', 'user.courseOrder', 'user.avatar'])->where('course_id', 'in', $coursesIds)->where('pay_status', OrderPayStatusEnum::SUCCESS)->distinct(true)->field('user_id')->select();
    }

    // 根据多个工作人员id获取多个课程
    public function getCoursesByEmployeeIds($ids)
    {
        return $this->with(['user', 'course'])->hasWhere('course', function ($query) use ($ids){
            $query->where('employee_id', 'in', $ids);
        })->where('pay_status', OrderPayStatusEnum::SUCCESS)->order('course_id asc')->select();
    }

    public function getInfoByOrderIdAndUserId($orderId, $user_id)
    {
        return $this->where('order_id', $orderId)->where('user_id', $user_id)->findOrEmpty();
    }

    // 统计指定课程的已付款人数
    public static function countPaidNums($courseId)
    {
        return self::where('course_id', $courseId)->where('pay_status', OrderPayStatusEnum::SUCCESS)->count();
    }

    public static function hasBought($userId, $courseId)
    {
        return self::where('course_id', $courseId)->where('user_id', $userId)->where('pay_status', OrderPayStatusEnum::SUCCESS)->findOrEmpty();
    }

}
